package blue.blog.pic;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.blue.crawler.annotation.CrawlerConfig;
import com.blue.crawler.annotation.CrawlerPathConfig;
import com.blue.crawler.engine.ListDetailCrawl;

import blue.blog.core.model.CmsDoc;
import blue.blog.core.service.CmsDocService;
import blue.blog.util.CmsDocConvertor;

@Component
public class MmjpgCrawl implements ListDetailCrawl<MmjpgModel>
{
	private static Logger logger = LoggerFactory.getLogger(MmjpgCrawl.class);
	
	//private static Pattern countPattern = Pattern.compile("\\[\\d{4},\\d+,(\\d+)\\,\\d+]");
	private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("发表于: yyyy年MM月dd日");
	
	@Resource
	private CmsDocService cmsDocService;
	
	public MmjpgCrawl()
	{
	}

	@Override
	public List<MmjpgModel> queryList(String html, CrawlerConfig config, CrawlerPathConfig pathConfig)
	{
		Document doc = Jsoup.parse(html);
		Elements aNodes = doc.select("div.main > div.pic > ul > li > a");
		List<MmjpgModel> list = new ArrayList<>();
		for (Element aNode : aNodes)
		{
			MmjpgModel result = new MmjpgModel();
			list.add(result);
			
			String url = aNode.attr("href").trim();
			result.setUrl(url);
			
			Element imgNode = aNode.select("img").first();
			if (imgNode != null)
			{
				String title = imgNode.attr("alt").trim();
				result.setTitle(title);
				
				String cover = imgNode.attr("src").trim();
				result.setCover(cover);
			}
		}
		
		return list;
	}

	@Override
	public List<String> query(String html, CrawlerConfig config, CrawlerPathConfig pathConfig, MmjpgModel model)
	{
		Document doc = Jsoup.parse(html);
		Element infoNode = doc.select("div.main > div.article > div.info > i").first();
		String strDate = infoNode.text().trim();
		model.setCreateTime(LocalDate.parse(strDate, dateFormatter).atStartOfDay());
		
		Elements imgNodes = doc.select("#content > a > img");
		List<String> picList = new ArrayList<>();
		StringBuilder content = new StringBuilder(256);
		
		for (Element imgNode : imgNodes)
		{
			String pic = imgNode.attr("src").trim();
			picList.add(pic);
			
			imgNode.removeAttr("alt");
			content.append(String.format("<p><img src=\"%s\" /></p>\n", pic));
		}
		model.setContent(content.toString());
		
		return picList;
	}

	@Override
	public List<String> queryPage(String html, CrawlerConfig config, CrawlerPathConfig pathConfig, MmjpgModel model, int page)
	{
		if (page > 1)
			return null;

		Document doc = Jsoup.parse(html);
		Elements aNodes = doc.select("#page > a");
		List<String> pageList = new ArrayList<>();
		if (aNodes != null && aNodes.size() > 2)
		{
			String url = aNodes.get(aNodes.size() - 2).attr("href").trim();
			//System.out.println(url);
			
			int pos = url.lastIndexOf('/');
			String baseUrl = url.substring(0, pos);
			int max = Integer.parseInt(url.substring(pos+1));
			//System.out.println(baseUrl + "----" + max);
			
			for (int i = 2; i <=max; i++)
			{
				pageList.add(baseUrl + "/" + i);
			}
		}
		
		return pageList;
	}

	@Override
	public boolean existUrl(String url)
	{
		return cmsDocService.exist(url);
	}

	@Override
	public void handleModel(CrawlerConfig config, CrawlerPathConfig pathConfig, MmjpgModel model)
	{
		CmsDoc doc = CmsDocConvertor.toDoc(model, 2);
		logger.info("保存：{}", model.getTitle());
		cmsDocService.add(doc);
	}
}
